package com.hele.sts.pub;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

@Service
public class ConnectDB {
	private static final Logger logger = LoggerFactory.getLogger(ConnectDB.class);

	Connection conn;

	
	private DataSource dataSource;
	
	private JdbcTemplate jt;
	
	public ConnectDB(DataSource dataSource){
		jt = new JdbcTemplate(dataSource);
	}

	/**
	 * @return the dataSource
	 */
	public DataSource getDataSource() {
		return dataSource;
	}

	/**
	 * @param dataSource the dataSource to set
	 */
	@Autowired
	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}

	public ConnectDB(String dataS) {
		this.conn = null;
		DataSource ds = null;
		if ((dataS == null) || (dataS.equals(""))) {
			dataS = PropGet.dataSourceName;
		}
		try {
			// Context ctx = new InitialContext();
			// ds = (DataSource)ctx.lookup(dataS);
			ds = dataSource;
			this.conn = ds.getConnection();
		} catch (Exception e) {
			logger.error("error datasource", e);
		}
	}

	public ConnectDB() {
		this.conn = null;
		DataSource ds = null;
		try {
			// Context ctx = new InitialContext();
			// ds = (DataSource)ctx.lookup(PropGet.dataSourceName);
			ds = dataSource;
			//this.conn = ds.getConnection();
		} catch (Exception e) {
			logger.error("error datasource", e);
		}
	}

	public void close() {
		try {
			if (this.conn != null) {
				this.conn.close();
			}
		} catch (SQLException localSQLException) {
			try {
				if (this.conn != null) {
					this.conn.close();
				}
			} catch (Exception e) {
			}
		} finally {
			try {
				if (this.conn != null) {
					this.conn.close();
				}
			} catch (Exception e) {
			}
		}
	}

	public Connection getConnection() throws SQLException {
		this.conn = dataSource.getConnection();
		return this.conn;
	}
}
